package com.sailfish.springbootdemo.service.db1;

import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.configs.UserHeaderHolder;
import com.sailfish.springbootdemo.dao.db1.PcbaDeviceDao;
import com.sailfish.springbootdemo.dao.db1.UpkeepDao;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db1.PcbaDevice;
import com.sailfish.springbootdemo.pojo.db1.Upkeep;
import com.sailfish.springbootdemo.pojo.db4.Operate;
import com.sailfish.springbootdemo.service.db4.OperateService;
import com.sailfish.springbootdemo.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class UpkeepServiceImpl implements UpkeepService {

    @Autowired
    private UpkeepDao upkeepDao;

    @Autowired
    private PcbaDeviceDao pcbaDeviceDao;

    @Qualifier("MysqlTransactionManager1")
    @Autowired
    private DataSourceTransactionManager transactionManager1;

    @Autowired
    private OperateService operateService;

    private String operateSmallType = "保养计划";

    @Override
    @Transactional(transactionManager = "MysqlTransactionManager1")
    public Result addUpkeep(Upkeep upkeep) {
        try {

            String userId = UserHeaderHolder.getUserId();

            upkeep.setCreateTime(new Date());
            String assetNumber = upkeep.getAssetNumber();
            PcbaDevice pcbaDevice = pcbaDeviceDao.getByAssetNumber(assetNumber);
            if (pcbaDevice != null) {
                upkeep.setPcbaDeviceId(pcbaDevice.getPcbaDeviceId());
                upkeepDao.addUpkeep(upkeep);

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 1, 1, new Date(), null, JSONObject.toJSONString(upkeep)));

                PcbaDevice oldPcbaDevice = pcbaDeviceDao.getById(pcbaDevice.getPcbaDeviceId());
                //将 is_filled_upkeep 改为 1
                PcbaDevice updatePcbaDevice = new PcbaDevice();
                updatePcbaDevice.setIsFilledUpkeep(1);
                updatePcbaDevice.setPcbaDeviceId(pcbaDevice.getPcbaDeviceId());
                updatePcbaDevice.setUpdateTime(new Date());
                pcbaDeviceDao.updatePcbaDevice(updatePcbaDevice);

                // 操作日志
                operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldPcbaDevice), JSONObject.toJSONString(updatePcbaDevice)));

                return ResultUtil.success(null);
            } else {
                return ResultUtil.error(500, "未找到对应资产的设备", "Not Found pcbaDevice", null);
            }

        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Transactional(transactionManager = "MysqlTransactionManager1")
    @Override
    public Result deleteUpkeep(Integer upkeepId) {
        try {
            if (upkeepId == null || "".equals(upkeepId.toString())) {
                return ResultUtil.error(500, "缺少参数upkeepId", "Miss Param upkeepId", null);
            }

            String userId = UserHeaderHolder.getUserId();

            Upkeep upkeep = upkeepDao.getById(upkeepId);
            // 删除保养计划
            upkeepDao.deleteUpkeepById(upkeepId);

            // 操作日志
            operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 2, 1, new Date(), JSONObject.toJSONString(upkeep), null));

            // 当 保养计划 全部删除 则 将 is_filled_upkeep 改为 2
            List<Upkeep> upkeeps = upkeepDao.judgeExistUpkeepByAssetNumber(upkeep.getAssetNumber(), upkeepId);
            if (upkeeps.size() == 0) {
                PcbaDevice updatePcbaDevice = new PcbaDevice();
                updatePcbaDevice.setIsFilledUpkeep(2);
                updatePcbaDevice.setPcbaDeviceId(upkeep.getPcbaDeviceId());
                updatePcbaDevice.setUpdateTime(new Date());
                pcbaDeviceDao.updatePcbaDevice(updatePcbaDevice);
            }
            return ResultUtil.success(null);
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return ResultUtil.error(500, e.getMessage(), e.getMessage(), null);
        }
    }

    @Override
    public Boolean updateUpkeep(Upkeep upkeep) throws Exception {

        String userId = UserHeaderHolder.getUserId();
        Upkeep oldUpkeep = upkeepDao.getById(upkeep.getUpkeepId());

        upkeep.setUpdateTime(new Date());
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date time = format.parse(upkeep.getFirstUpkeepTimeStr());
        upkeep.setFirstUpkeepTime(time);

        // 操作记录
        operateService.addOperate(new Operate(1, Integer.parseInt(userId), operateSmallType, 3, 1, new Date(), JSONObject.toJSONString(oldUpkeep), JSONObject.toJSONString(upkeep)));

        return upkeepDao.updateUpkeep(upkeep) > 0;
    }

    @Override
    public List<Upkeep> getUpkeepByAssetNumber(String assetNumber) {
        return upkeepDao.getUpkeepByDeviceId(assetNumber, null);
    }
}
